<?php


namespace Xy\Rbac\Exceptions;

use Throwable;

class BaseException extends \Exception
{
    private $_code;
    public $status;
    private $_returnMessage;

    protected $defaultMsg
        = [
            'message' => '这个api找不到了,别担心!我们已经派出最牛的人在修复...'
        ];

    protected $exceptionMessage = [];
    private $_HTTP_STATUS
        = [
            401 => ['message' => "未授权，请登录。"],
            403 => ['message' => "拒绝访问。"],
            404 => ['message' => "请求方法不存在。"],
            405 => ['message' => "禁止操作。"],
            407 => ['message' => "没有权限。"],
            415 => ['message' => "请求类型错误。"],
            422 => ['message' => "请求参数有误。"],
            408 => ['message' => "请求超时。"],
            500 => ['message' => "服务器内部错误"],
            501 => ['message' => "服务器不支持当前请求所需要的某个功能。"],
        ];

    public function __construct(int $code, int $status = 200, $returnMessage = "", Throwable $previous = null)
    {
        $this->status = $status;
        $this->_code = $code;
        $this->_returnMessage = $returnMessage;
        $this->exceptionMessage += $this->_HTTP_STATUS;
        $message = $this->getExceptionMessage();
        parent::__construct($message, $code, $previous);
    }


    public function getExceptionMessage()
    {
        $codeMessage = $this->_getCodeMessage($this->_code);
        return empty($this->_returnMessage) ? $codeMessage : $this->_returnMessage;
    }

    private function _getCodeMessage(int $code)
    {
        return ($this->exceptionMessage[$code] ?? [])['message'] ?? $this->defaultMsg['message'];
    }
}